/**
 * Copyright 2008 Hotye Inc.
 */
package craneding.gwt.databean.client.ui.field;

import com.google.gwt.user.client.ui.ListBox;

import craneding.gwt.databean.client.model.EnumType;
import craneding.gwt.databean.client.model.FieldInfo;
import craneding.gwt.databean.client.model.FieldMetaData;

/**
 * like ListBox <h3>CSS Style Rules</h3> <ul class='css'> <li>
 * .DataBean-SelectFieldInput{ primary style }</li> </ul>
 * 
 * @author crane.ding
 * @version 1.0 2008-12-2
 */
public class SelectFieldInput extends ListBox implements IFieldInput {
	private FieldInfo fieldInfo;
	private String fieldName;
	private EnumType<?>[] enumTypes;

	public SelectFieldInput() {
		setStyleName("DataBean-SelectFieldInput");
	}

	public Object getValue() {
		int index = getSelectedIndex();
		if (index == -1)
			return null;
		EnumType<?>[] types = ((FieldMetaData) fieldInfo).enumerations();

		if (fieldInfo.enumKey() != Object.class) {
			for (EnumType<?> enumType : types) {
				if (enumType.key().toString().equals(getValue(index)))
					return enumType;
			}
		} else {
			for (EnumType<?> enumType : types) {
				if (enumType.key().toString().equals(getValue(index)))
					return enumType.key();
			}
		}

		return null;
	}

	public void setFieldInfo(String fieldName, FieldInfo fieldInfo) {
		this.fieldName = fieldName;
		this.fieldInfo = fieldInfo;
		setMetaData();
	}

	private void setMetaData() {
		setName(fieldName);
		FieldMetaData metaData = (FieldMetaData) fieldInfo;
		if (!fieldInfo.description().equals(""))
			setTitle(this.fieldInfo.description());
		if (!fieldInfo.required())
			addItem("请选择" + fieldInfo.label(), "");
		enumTypes = metaData.enumerations();
		if (enumTypes != null) {
			for (EnumType<?> enumType : enumTypes) {
				Object value = enumType.key();
				String item = enumType.label();
				addItem(item, value.toString());
			}
		}
	}

	public void setValue(Object value) {
		if (value == null)
			return;
		int itemCount = getItemCount();
		for (int index = 0; index < itemCount; index++) {
			String value2 = getValue(index);
			if (value2.equals(((EnumType<?>) value).key())) {
				setSelectedIndex(index);
				break;
			}
		}
	}

	public void validityCheck() throws ValidationException {

	}
}
